/*
 * @Author: CPS
 * @Date: 2020-07-19 20:40:40
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-05 22:40:20
 * @Projectname Electron-fileWatcher
 * @Filename getFolderSize.js
 */
'use strict'
import fs from 'fs'
import path from 'path'

/**
 * Gets the file size.
 *
 * @param      {number}  total   The total
 * @param      {string}  unit    The unit
 * @return     {number}  The file size.
 */
export function getFileSize(fileSize) {
  if (fileSize < 1024) {
    return fileSize + 'B';
  } else if (fileSize < (1024 * 1024)) {
    let temp = fileSize / 1024;
    temp = temp.toFixed(2);
    return temp + 'KB';
  } else if (fileSize < (1024 * 1024 * 1024)) {
    let temp = fileSize / (1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'MB';
  } else {
    let temp = fileSize / (1024 * 1024 * 1024);
    temp = temp.toFixed(2);
    return temp + 'GB';
  }
}

/**
 * 获取文件夹的大小，返回byte格式
 *
 * @param      {<type>}             tar     The tar
 * @param      {(Function|number)}  count   The count
 * @return     {<type>}             The floder size.
 */
function iterationFloderSize(tar, count = 0) {
  count = count / (1024 * 1024 * 1024)
  let res;
  if (fs.lstatSync(tar).isFile()) {
    return fs.lstatSync(tar).size + count

  } else if (fs.lstatSync(tar).isDirectory()) {

    let fileList = fs.readdirSync(tar)
    if (fileList.length > 0) {
      fileList.forEach(item => {
        count += iterationFloderSize(path.resolve(tar, item), count)
      })
    }
  }
  return count
}

export function getFolderSize(target) {
  try {
    return getFileSize(iterationFloderSize(target))
  } catch (e) {
    console.log(target)
    console.log(e)
  }
}